package com.android.plc.ui;

import java.io.Serializable;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.plc.CONST;
import com.android.plc.CONST.COMMAND;
import com.android.plc.CONST.SOCKSTATE;
import com.android.plc.R;
import com.android.plc.classholder.BasicItem;
import com.android.plc.classholder.BasicItem.Type;
import com.android.plc.classholder.Device;
import com.android.plc.classholder.Profile;
import com.android.plc.classholder.Room;
import com.android.plc.engine.Command;
import com.android.plc.engine.NetWorkManager;
import com.android.plc.engine.NetWorkManager.OnNetworkEventListener;
import com.android.plc.provider.PLC;
import com.android.plc.provider.PLC.Servers;
import com.android.plc.ui.IBaseManager.Manager;
import com.android.plc.ui.adapter.DeviceAdapter;
import com.android.plc.ui.adapter.EditorAdapter;
import com.android.plc.ui.adapter.EditorAdapter.onChangeListener;
import com.android.plc.ui.adapter.RoomAdapter;
import com.android.plc.ui.control.AirControl;
import com.android.plc.ui.control.AudioControl;
import com.android.plc.ui.control.BackAudioControl;
import com.android.plc.ui.control.BaseControl;
import com.android.plc.ui.control.BoxControl;
import com.android.plc.ui.control.DVDControl;
import com.android.plc.ui.control.DimControl;
import com.android.plc.ui.control.HomeRemoteControl;
import com.android.plc.ui.control.NormalControl;
import com.android.plc.ui.control.ProfileControl;
import com.android.plc.ui.control.ProjectorControl;
import com.android.plc.ui.control.RoomControl;
import com.android.plc.ui.control.SafeControl;
import com.android.plc.ui.control.TVControl;
import com.android.plc.ui.manager.BaseManager;
import com.android.plc.ui.manager.DeviceListManager;
import com.android.plc.ui.manager.DeviceManager;
import com.android.plc.ui.manager.HomeRemoteMagager;
import com.android.plc.ui.manager.ProfileListManager;
import com.android.plc.ui.manager.ProfileManager;
import com.android.plc.ui.manager.RoomListManager;
import com.android.plc.ui.manager.RoomManager;
import com.android.plc.ui.view.PanelControlView;
import com.android.plc.ui.view.VerticalGallery;
import com.android.plc.ui.view.VerticalGalleryAdapterView;
import com.android.plc.util.PrefUtil;

public class ControlManager implements OnNetworkEventListener, OnItemSelectedListener,
		OnSharedPreferenceChangeListener, com.android.plc.ui.view.VerticalGalleryAdapterView.OnItemSelectedListener,
		onChangeListener
{
	private static final String TAG = "ControlManager";

	public static final int MSG_COMMAND = 0x1000;
	public static final int DEF_USER_CODE = 0x00;
	public static final boolean DEF_IS_SINGLE = true;

	private PanelControlView mPanelControlView;
	private LinearLayout mConnectionNotice;
	private Context mContext;
	private DeviceListManager mDeviceListManager;
	private ProfileListManager mProfileListManager;
	private RoomListManager mRoomListManager;
	private NetWorkManager mNetWorkManager = null;

	private BaseManager mBaseMagager;

	private BaseControl mDeviceControl;
	private boolean mAdminMode = false;
	private Device mCurrentDevice;
	private Device mTmpDevice;
	private Room mCurrentRoom;
	private Profile mCurrentProfile;

	private VerticalGallery mRoomList;
	private VerticalGallery mDeviceList;
	private Gallery mProfileList;

	// Time changed flag
	private boolean mHomeControl = false;
	private int mUserCode = DEF_USER_CODE;
	private boolean mIsSingle = DEF_IS_SINGLE;

	public ControlManager(Context context, ViewGroup main)
	{
		mContext = context;
		mPanelControlView = (PanelControlView) main.findViewById(R.id.manager_view);
		mConnectionNotice = (LinearLayout) main.findViewById(R.id.notice);

		mCurrentDevice = new Device(Type.ALL_ITEM);
		mCurrentRoom = new Room(Type.ALL_ITEM);
		mCurrentProfile = new Profile(Type.ALL_ITEM);

		switchControl(mCurrentDevice);

		mDeviceListManager = new DeviceListManager(context);
		EditorAdapter deviceAdapter = mDeviceListManager.getAdapter();
		deviceAdapter.setOnChangeListener(this);
		mDeviceList = (VerticalGallery) main.findViewById(R.id.list_devices);
		mDeviceList.setAdapter(deviceAdapter);
		mDeviceList.setSelection(0);
		mDeviceList.setOnItemSelectedListener(this);

		mProfileListManager = new ProfileListManager(context);
		mProfileList = (Gallery) main.findViewById(R.id.list_profile);
		mProfileList.setAdapter(mProfileListManager.getAdapter());
		mProfileList.setOnItemSelectedListener(this);
		mProfileList.setSelection(0);
		// mProfileList.getSelectedView().setPressed(true);

		mRoomListManager = new RoomListManager(context);
		EditorAdapter roomAdapter = mRoomListManager.getAdapter();
		roomAdapter.setOnChangeListener(this);
		mRoomList = (VerticalGallery) main.findViewById(R.id.list_rooms);
		mRoomList.setAdapter(roomAdapter);
		mRoomList.setSelection(0);
		mRoomList.setOnItemSelectedListener(this);

		SharedPreferences prefs = PrefUtil.getPreferences(mContext);
		int user_code = prefs.getInt(PrefUtil.PREF_USER_CODE, DEF_USER_CODE);
		mUserCode = Math.min(250, Math.max(1, user_code));
		mIsSingle = prefs.getBoolean(PrefUtil.PREF_IS_SINGLE, DEF_IS_SINGLE);

		prefs.registerOnSharedPreferenceChangeListener(this);
		refreshUI();
	}

	public void swtichControl()
	{
		mProfileList.setSelection(0);
		mProfileList.invalidate();
		// mProfileList.getSelectedView().setSelected(true);
		// mProfileList.getSelectedView().invalidate();
	}

	public void notifyBasicItemSelected(Manager mgr, BasicItem item)
	{
		switch (mgr)
		{
		case ROOM:
			if (mDeviceListManager != null)
				mDeviceListManager.onBasicItemSelected(Manager.ROOM, item, mAdminMode);
			if (mDeviceList != null)
			{
				if (item.type == Type.ADD_ITEM && item._id > 0)
				{
					try
					{
						mRoomList.setSelection(mRoomList.getCount());
						mDeviceList.setSelection(1);
					} catch (Exception e)
					{
					}
				}
				if (mTmpDevice != null)
				{
					mTmpDevice = null;
				} else
				{
					if (mAdminMode && item.type == Type.NORMAL_ITEM)
					{
						mDeviceList.setSelection(1);
					} else
					{
						mDeviceList.setSelection(0);
					}
				}

			}

			break;
		case DEVICE:
			if (item.type == Type.ADD_ITEM && item._id > 0)
			{
				try
				{
					mDeviceList.setSelection(mDeviceList.getCount());
				} catch (Exception e)
				{
				}
			}
			if (mTmpDevice != null)
			{
				mTmpDevice = null;
			}
			break;
		case PROFILE:
			break;
		default:
			break;
		}

	}

	private Handler uiHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);

			switch (msg.what)
			{
			case MSG_COMMAND:
				Bundle data = msg.getData();
				Command command = data.getParcelable("DATA");
				command.COMMAND = convCommand(command.COMMAND, false);
				int onid = mIsSingle ? COMMAND.ALLHOMEONID : COMMAND.ALLHOMEONID_3;
				if (command.COMMAND == onid)
				{
					int status = ((command.DATA1 << 8) + command.DATA2) % 0xFFFF;

					for (int i = 0; i < 16; i++)
					{
						int cmd = (status % 2 == 1) ? COMMAND.ON : COMMAND.OFF;
						status /= 2;
						mDeviceListManager.setDeviceOn(command.HOME_UNIT + i, cmd);
					}
					mDeviceList.invalidate();
				} else
				{
					if (command.COMMAND == COMMAND.ON || command.COMMAND == COMMAND.OFF
							|| command.COMMAND == COMMAND.STATUSON || command.COMMAND == COMMAND.STATUSOFF)
					{
						mDeviceListManager.setDeviceOn(command.HOME_UNIT, command.COMMAND);
						mDeviceList.invalidate();
					}
					if (mCurrentDevice != null && mCurrentDevice.code == command.HOME_UNIT)
					{
						mDeviceControl.onReceive(command.COMMAND, command.DATA1, command.DATA2);
					}
				}
				break;
			default:
				break;
			}
		}

	};

	public void onReceive(Command cmd)
	{
		Message msg = Message.obtain();
		msg.what = MSG_COMMAND;
		Bundle data = new Bundle();
		data.putParcelable("DATA", cmd);
		msg.setData(data);
		uiHandler.sendMessage(msg);
	}

	public void sendControlCommand(int offset, int comand, int data1, int date2)
	{
		if (mNetWorkManager != null)
		{
			int home_unit = 0x00;
			if (comand == COMMAND.ALLHOMEONID || comand == COMMAND.ALLHOMEUNITOFF || comand == COMMAND.ALLHOMELTSON)
			{
				if (mCurrentRoom != null)
				{
					home_unit = mCurrentRoom.code << 4;
				}
			} else if (comand == COMMAND.ALLUSERLTSON || comand == COMMAND.ALLUSERLTSOFF)
			{
				home_unit = 0x00;
			} else
			{
				if (mCurrentDevice != null)
				{
					home_unit = mCurrentDevice.code + offset;
				}
			}
			mNetWorkManager.sendCommand(mUserCode, home_unit, convCommand(comand, true), data1, date2);
		}
	}

	public void sendUnitCommand(int home_unit, int comand, int data1, int date2)
	{
		if (mNetWorkManager != null)
		{
			mNetWorkManager.sendCommand(mUserCode, home_unit, convCommand(comand, true), data1, date2);
		}
	}

	public void release()
	{
		SharedPreferences prefs = PrefUtil.getPreferences(mContext);
		prefs.unregisterOnSharedPreferenceChangeListener(this);

		if (mNetWorkManager != null)
		{
			mNetWorkManager.release();
			mNetWorkManager = null;
		}
	}

	public void setDeviceControl(BaseControl bc)
	{
		mDeviceControl = bc;
	}

	public void switchManager(Manager mgr, BasicItem item)
	{

		boolean showProfile = mCurrentProfile.type != Type.ALL_ITEM;
		boolean showRoom = mCurrentRoom.type == Type.ADD_ITEM
				|| (mCurrentRoom.type == Type.NORMAL_ITEM && (mCurrentDevice == null || mCurrentDevice.type == Type.ALL_ITEM))
				|| (mCurrentRoom.type == Type.ALL_ITEM && (mCurrentDevice == null || mCurrentDevice.type == Type.ADD_ITEM));
		boolean showHomeMgr = mCurrentRoom.type == Type.ALL_ITEM && mCurrentDevice.type == Type.ALL_ITEM;
		boolean showDevice = !(showProfile || showRoom || showHomeMgr);
		boolean sameManager = showProfile == (mBaseMagager instanceof ProfileManager);
		sameManager = sameManager && (showRoom == (mBaseMagager instanceof RoomManager));
		sameManager = sameManager && (showHomeMgr == (mBaseMagager instanceof HomeRemoteMagager));
		sameManager = sameManager && (showDevice == (mBaseMagager instanceof DeviceManager));
		if (!sameManager)
		{
			if (mBaseMagager != null)
			{
				mBaseMagager.detachFromControlManager(mPanelControlView);
				mBaseMagager = null;
			}
			if (showProfile)
			{
				mBaseMagager = new ProfileManager(mContext, mPanelControlView);
			} else if (showRoom)
				mBaseMagager = new RoomManager(mContext, mPanelControlView);
			else if (showHomeMgr)
				mBaseMagager = new HomeRemoteMagager(mContext, mPanelControlView);
			else if (showDevice)
				mBaseMagager = new DeviceManager(mContext, mPanelControlView);

			if (mBaseMagager != null)
			{
				mBaseMagager.setControlManager(this);
				mBaseMagager.attachToControlManager(mPanelControlView);
			}
		}
		mBaseMagager.onBasicItemSelected(mgr, item, mAdminMode);
	}

	public void switchControl(BasicItem item)
	{
		if (mDeviceControl != null)
		{
			mDeviceControl.detachFromControlManager(mPanelControlView);
			mDeviceControl = null;
		}

		if (item instanceof Device)
		{
			Device device = (Device) item;

			if (device != null && (device.type == Type.ALL_ITEM || device.type == Type.ADD_ITEM))
			{
				if (mCurrentRoom.type == Type.ALL_ITEM)
				{
					mDeviceControl = new HomeRemoteControl(mContext, mPanelControlView);
				} else if (mCurrentRoom.type == Type.NORMAL_ITEM)
				{
					mDeviceControl = new RoomControl(mContext, mPanelControlView);
				}
			} else if (device != null && device.type == Type.NORMAL_ITEM)
			{
				switch (device.device_type)
				{
				case CONST.DEVICETYPE.DEVICETYPE_DEFAULT:
					mDeviceControl = new NormalControl(mContext, mPanelControlView);
					break;
				case CONST.DEVICETYPE.DEVICETYPE_DIM:
					mDeviceControl = new DimControl(mContext, mPanelControlView);
					break;
				case CONST.DEVICETYPE.DEVICETYPE_IR:
				{
					switch (device.sub_type)
					{
					case CONST.IRTYPE.IRTYPE_AUDIO: // _amp
						mDeviceControl = new AudioControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_BACKAUDIO: // _back
						mDeviceControl = new BackAudioControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_BOX: // _stb
						mDeviceControl = new BoxControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_DVD: // _dvd
						mDeviceControl = new DVDControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_HOME:
						break;
					case CONST.IRTYPE.IRTYPE_PROJECTION: // _proj
						mDeviceControl = new ProjectorControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_SAFE: // _sec
						mDeviceControl = new SafeControl(mContext, mPanelControlView);
						break;
					case CONST.IRTYPE.IRTYPE_TV:
						mDeviceControl = new TVControl(mContext, mPanelControlView);
						break;
					default:
						break;
					}
				}
					break;
				case CONST.DEVICETYPE.DEVICETYPE_AIR_CONDITION: // _air
					mDeviceControl = new AirControl(mContext, mPanelControlView);
					break;

				default:
					break;
				}
			}

			if (mDeviceControl != null)
			{
				mDeviceControl.setControlManager(this);
				mDeviceControl.attachToControlManager(mPanelControlView);
			}

			if (device != null && device.type == Type.NORMAL_ITEM)
			{
				int command = mDeviceListManager.isDeviceOn(device.code) ? COMMAND.ON : COMMAND.OFF;
				mDeviceControl.onReceive(command, 0, 0);
			}
		} else if (item instanceof Profile)
		{
			mDeviceControl = new ProfileControl(mContext, mPanelControlView);

			if (mDeviceControl != null)
			{
				mDeviceControl.setControlManager(this);
				mDeviceControl.attachToControlManager(mPanelControlView);
			}
		}
	}

	public void setConnectionStatus(int status)
	{
		if (mConnectionNotice == null)
			return;
		TextView text = (TextView) mConnectionNotice.findViewById(R.id.textNotice);
		ProgressBar progress = (ProgressBar) mConnectionNotice.findViewById(R.id.progress);

		String message = "";
		boolean showProgress = false;
		boolean hide = false;
		switch (status)
		{

		case SOCKSTATE.SOCKSTATE_MOBILE:
			message = mContext.getString(R.string.socket_status_nowifi);
			break;
		case SOCKSTATE.SOCKSTATE_SCANNING:
			message = mContext.getString(R.string.socket_status_scanning);
			showProgress = true;
			break;
		case SOCKSTATE.SOCKSTATE_CONNECTING:
			message = mContext.getString(R.string.socket_status_connecting);
			showProgress = true;
			break;
		case SOCKSTATE.SOCKSTATE_CONNECTERROR:
			message = mContext.getString(R.string.socket_status_error);
			break;
		case SOCKSTATE.SOCKSTATE_OPENED:
			message = mContext.getString(R.string.socket_status_opened);
			hide = true;
			break;
		case SOCKSTATE.SOCKSTATE_NONETWORK:
		default:
			message = mContext.getString(R.string.socket_status_nonetwork);
			break;
		}
		if (hide)
		{
			mHandler.removeMessages(MSG_HIDE);
			mHandler.sendEmptyMessageDelayed(MSG_HIDE, 3000);
		} else
		{
			mConnectionNotice.setVisibility(View.VISIBLE);
		}
		text.setText(message);
		progress.setVisibility(showProgress ? View.VISIBLE : View.GONE);
	}

	public void onNetworkStatusChanged(int status)
	{
		Message msg = Message.obtain();
		msg.arg1 = status;
		msg.what = MSG_SET_STATUS;
		mHandler.sendMessage(msg);
	}

	private static final int MSG_SET_STATUS = 0x01;
	private static final int MSG_SELECT_DEVICE = 0x02;
	private static final int MSG_SELECT_ROOM = 0x03;
	private static final int MSG_SELECT_PROFILE = 0x04;
	private static final int MSG_HIDE = 0x10;
	private static final int MSG_SELECT_DELAY = 500;

	private Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case MSG_SET_STATUS:
				setConnectionStatus(msg.arg1);
				break;
			case MSG_HIDE:
				mConnectionNotice.setVisibility(View.INVISIBLE);
				break;
			case MSG_SELECT_PROFILE:
			case MSG_SELECT_ROOM:
			case MSG_SELECT_DEVICE:
				Bundle data = msg.getData();
				if (data != null)
				{
					Serializable serializable = data.getSerializable("DATA");
					if (serializable != null)
					{
						onItemSelected((BasicItem) serializable);
					}
				}
				break;
			default:
				break;
			}
		}
	};

	public void setAdminMode(boolean admin)
	{
		mDeviceListManager.getAdapter().setEditMode(admin);
		mRoomListManager.getAdapter().setEditMode(admin);
		mProfileListManager.getAdapter().setEditMode(admin);
		mTmpDevice = new Device(mCurrentDevice);
		boolean last = mAdminMode;
		mAdminMode = admin;
		if (mRoomList != null)
		{
			int index = mRoomList.getSelectedItemPosition();
			if (admin != last)
			{
				index += admin ? 1 : -1;
				if (index == -1)
				{
					onItemSelected((BasicItem) mRoomListManager.getAdapter().getItem(0));
					// onItemSelected((BasicItem) mRoomList.getSelectedItem());
				} else
				{
					mRoomList.setSelection(index);
				}
			}
			mRoomListManager.getAdapter().notifyDataSetChanged();
			mRoomList.invalidate();
		}
		if (mDeviceList != null)
		{
			if (admin != last)
			{
				int index = mDeviceList.getSelectedItemPosition();
				index += admin ? 1 : -1;
				if (index == -1)
				{
					// onItemSelected((BasicItem)
					// mDeviceListManager.getAdapter().getItem(0));
				} else
				{
					mDeviceList.setSelection(index);
				}
			}
			mDeviceListManager.getAdapter().notifyDataSetChanged();
			mDeviceList.invalidate();
		}
		if (mProfileList != null)
		{
			int index = mProfileList.getSelectedItemPosition();
			if (admin != last && index > 0)
			{
				index += admin ? 1 : -1;
			}
			mProfileList.setSelection(index);
			mProfileList.invalidate();
		}
	}

	public boolean isAdminMode()
	{
		return mAdminMode;
	}

	public void setDevice(Device mCurrentDevice)
	{
		this.mCurrentDevice = mCurrentDevice;
	}

	public Device getDevice()
	{
		return mCurrentDevice;
	}

	public void setRoom(Room room)
	{
		this.mCurrentRoom = room;
	}

	public Room getRoom()
	{
		return mCurrentRoom;
	}

	@TargetApi(11)
	private void refreshUI()
	{
		//
		boolean showProfile = mAdminMode && mCurrentProfile != null && mCurrentProfile.type != Type.ALL_ITEM;

		if (mDeviceControl != null)
		{
			mDeviceControl.getView().setVisibility(mAdminMode ? View.INVISIBLE : View.VISIBLE);
		}

		if (mBaseMagager != null)
		{
			mBaseMagager.getView().setVisibility(mAdminMode ? View.VISIBLE : View.INVISIBLE);
		}

		if (mDeviceList != null)
		{
			((ViewGroup) mDeviceList.getParent()).setVisibility(showProfile ? View.INVISIBLE : View.VISIBLE);
		}
		if (mRoomList != null)
		{
			((ViewGroup) mRoomList.getParent()).setVisibility(showProfile ? View.INVISIBLE : View.VISIBLE);
		}
		boolean profileControl = mCurrentProfile != null && mCurrentProfile.type == Type.NORMAL_ITEM;
		// Build.VERSION_CODES.HONEYCOMB
		if (Build.VERSION.SDK_INT >= 11)
		{
			((View) mRoomList.getParent()).setAlpha(profileControl ? 0.5f : 1);
			((View) mDeviceList.getParent()).setAlpha(profileControl ? 0.5f : 1);
		} else
		{
			mRoomList.setAlpha(profileControl ? 128 : 255);
			mDeviceList.setAlpha(profileControl ? 128 : 255);
		}
	}

	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		BasicItem item = (BasicItem) mProfileList.getItemAtPosition(arg2);
		if (item == null)
		{
			return;
		}
		Message msg = Message.obtain();
		msg.what = MSG_SELECT_PROFILE;

		Log.d(TAG, "onItemSelected BasicItem " + item);

		Bundle data = new Bundle();
		data.putSerializable("DATA", item);
		msg.setData(data);

		mHandler.removeMessages(MSG_SELECT_PROFILE);
		mHandler.sendMessageDelayed(msg, MSG_SELECT_DELAY);
	}

	public void onNothingSelected(AdapterView<?> arg0)
	{
		swtichControl();
	}

	public Profile getProfile()
	{
		return mCurrentProfile;
	}

	private boolean init = false;

	public void setHomeCtrol(boolean home)
	{
		if (init == true && mHomeControl == home)
			return;
		init = true;
		mHomeControl = home;

		SharedPreferences pref = PrefUtil.getPreferences(mContext);
		Editor editor = pref.edit();
		editor.putBoolean(PrefUtil.PREF_HOME_CONTROL, mHomeControl);
		editor.commit();

		Resources res = mContext.getResources();
		String address = res.getString(R.string.default_address);
		if (home)
		{
			ContentResolver resolver = mContext.getContentResolver();
			String column[] =
			{ Servers.ADDRESS };
			Cursor query = resolver.query(PLC.Servers.CONTENT_URI, column, null, null, null);
			if (query.moveToNext())
			{
				address = query.getString(0);
			}
			query.close();
		} else
		{
			address = pref.getString(PrefUtil.PREF_ROMOTE_ADDRESS, address);
		}
		if (mNetWorkManager == null)
		{
			mNetWorkManager = new NetWorkManager(mContext, this);
		}
		if (mNetWorkManager.getSocketStatus() == SOCKSTATE.SOCKSTATE_NONETWORK)
		{
			AlertDialog dialog = new AlertDialog.Builder(mContext).setTitle(R.string.no_wifi)
					.setMessage(R.string.enable_wifi)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int which)
						{
							mContext.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
						}
					}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener()
					{
						public void onClick(DialogInterface dialog, int which)
						{
						}
					}).create();
			dialog.show();
		} else
		{
			mNetWorkManager.connectTo(home, address);
		}
	}

	public void onSharedPreferenceChanged(SharedPreferences prefs, String key)
	{
		if (PrefUtil.PREF_USER_CODE.equals(key))
		{
			int user_code = prefs.getInt(PrefUtil.PREF_USER_CODE, DEF_USER_CODE);
			mUserCode = Math.min(250, Math.max(1, user_code));
		} else if (PrefUtil.PREF_IS_SINGLE.equals(key))
		{
			mIsSingle = prefs.getBoolean(PrefUtil.PREF_IS_SINGLE, DEF_IS_SINGLE);
		}
	}

	private int convCommand(int raw_command, boolean send)
	{
		int offset = mIsSingle ? 0x00 : 0x60;
		if (send)
		{
			// format 000XXXXX
			return (raw_command & 0x1F) + offset;
		} else
		{
			return (raw_command - offset) & 0x1F;
		}
	}

	public void onItemSelected(BasicItem item)
	{
		boolean showProfile = getProfile().type != Type.ALL_ITEM;
		if (item instanceof Room)
		{
			Room room = (Room) item;
			mCurrentRoom = room;
			if (mAdminMode && !showProfile)
			{
				notifyBasicItemSelected(Manager.ROOM, room);
				switchManager(Manager.ROOM, room);
			} else if (!mAdminMode && !showProfile)
			{
				notifyBasicItemSelected(Manager.ROOM, room);
				switchControl(mCurrentDevice);
			}
			Log.d(TAG, "onChanged ROOM " + room);
		}
		if (item instanceof Device)
		{
			Device device = (Device) item;
			mCurrentDevice = device;
			if (mAdminMode && !showProfile)
			{
				notifyBasicItemSelected(Manager.DEVICE, device);
				switchManager(Manager.DEVICE, device);
			} else if (!mAdminMode && !showProfile)
			{
				notifyBasicItemSelected(Manager.DEVICE, device);
				switchControl(mCurrentDevice);
			}
			Log.d(TAG, "onChanged DEVICE " + device);
		}
		if (item instanceof Profile)
		{
			Profile profile = (Profile) item;
			mCurrentProfile = profile;
			if (mAdminMode)
			{
				switchManager(Manager.PROFILE, profile);
			} else if (profile.type == Type.ALL_ITEM)
			{
				switchControl(mCurrentDevice);
			} else
			{
				switchControl(mCurrentProfile);
			}
			Log.d(TAG, "onChanged PROFILE " + profile);
		}
		refreshUI();
	}

	public void onItemSelected(VerticalGalleryAdapterView<?> parent, View view, int position, long id)
	{
		Message msg = Message.obtain();
		int meg_id = MSG_SELECT_DEVICE;
		EditorAdapter adapter = (EditorAdapter) parent.getAdapter();
		BasicItem item = (BasicItem) adapter.getItem(position);
		if (item instanceof Room)
		{
			meg_id = MSG_SELECT_ROOM;
		}
		Log.d(TAG, "onItemSelected BasicItem " + item);
		Bundle data = new Bundle();
		data.putSerializable("DATA", item);
		msg.what = meg_id;
		msg.setData(data);

		mHandler.removeMessages(meg_id);
		mHandler.sendMessageDelayed(msg, MSG_SELECT_DELAY);
	}

	public void onNothingSelected(VerticalGalleryAdapterView<?> parent)
	{

	}

	public void onChange(BaseAdapter adapter)
	{
		if (adapter instanceof RoomAdapter)
		{
			int position = Math.min(mRoomList.getSelectedItemPosition(), adapter.getCount() - 1);
			onItemSelected(mRoomList, null, position, 0);
		}

		if (adapter instanceof DeviceAdapter)
		{
			int position = Math.min(mDeviceList.getSelectedItemPosition(), adapter.getCount() - 1);
			onItemSelected(mDeviceList, null, position, 0);
		}
	}
}
